from django.http import HttpResponse
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login
from .forms import LoginForm
from .forms import RegisterForm

# Create your views here.

def register_view(request):
    if request.method == 'POST':
        form = RegisterForm(request.POST)
        if form.is_valid():
            print("表单数据:", form.cleaned_data)  # 打印表单数据
            user = form.save()  # 保存用户信息
            print("用户已创建:", user.username)  # 打印创建的用户
            login(request, user)  # 注册后自动登录
            return redirect('home')  # 修改为你的首页URL
        else:
            print("表单验证失败:", form.errors)  # 打印表单错误
    else:
        form = RegisterForm()
    return render(request, 'register.html', {'form': form})

def login_view(request):
    if request.method == 'POST':
        form = LoginForm(request, data=request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user)
                return redirect('home')  # 修改为你的首页URL
        return render(request, 'login.html', {'form': form})
    else:
        form = LoginForm()
    return render(request, 'login.html', {'form': form})

def index(request):
    return HttpResponse('hello')